﻿using System;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Web.DynamicData;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NotAClue.ComponentModel.DataAnnotations;
using NotAClue.Web.DynamicData;

namespace DD_Extensions
{
    public partial class IntegerRange_EditField : System.Web.DynamicData.FieldTemplateUserControl
    {
        RangeAttribute range;

        protected void Page_Init(object sender, EventArgs e)
        {
            // add tool-tip
            this.SetupTip();

            // set field options
            this.SetFieldOptions();

            // add CSS from meta data
            this.ApplyCss();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            range = MetadataAttributes.GetAttribute<RangeAttribute>();
            if (range == null)
                range = new RangeAttribute(1, 10);

            DropDownList1.ToolTip = Column.Description;

            if (DropDownList1.Items.Count == 0)
            {
                DropDownList1.Items.Clear();
                if (Mode == DataBoundControlMode.Insert || !Column.IsRequired)
                    DropDownList1.Items.Add(new ListItem("[-]", ""));

                for (int i = (int)range.Minimum; i <= (int)range.Maximum; i++)
                    DropDownList1.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }

            SetUpValidator(RequiredFieldValidator1);
            SetUpValidator(CompareValidator1);
            SetUpValidator(RangeValidator1);
            SetUpValidator(DynamicValidator1);

            // set validators to use image as error indicator
            this.SetValidatorsToImage();

            // check to see if column is read only in insert mode
            Column.DisableFieldTemplate(Mode, DropDownList1);
        }

        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);
            ListItem item = DropDownList1.Items.FindByValue(FieldValueString);
            if (item != null)
                DropDownList1.SelectedValue = FieldValueString;
        }

        protected override void ExtractValues(IOrderedDictionary dictionary)
        {
            dictionary[Column.Name] = ConvertEditedValue(DropDownList1.SelectedValue);
        }

        public override Control DataControl
        {
            get { return DropDownList1; }
        }
    }
}
